﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxControlToolkit;

namespace DistributedSystems
{
    public partial class Default : System.Web.UI.Page
    {
        DistributedSystemsDataContext db = new DistributedSystemsDataContext();

        protected void Page_Load(object sender, EventArgs e)
        {
            DateMin = DateTime.Now;
            if (this.IsPostBack == false)
            {
 
            }
        }

        #region Check input

        protected bool CheckPostcodeAndAdress(int postcode)
        {
            try
            {
                var pcResult = db.PostCodes.Where(p => p.PCode == postcode).ToList();
                return pcResult == null ? false : true;
            }
            catch (Exception ex)
            {
                return false;
            }


        }
        #endregion

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (!this.IsValid)//if error
            {
                Response.Redirect("~/Default.aspx",false);
            }            
        }
 
        private DateTime DateMin;
        protected void Calendar_DayRender(object sender, DayRenderEventArgs e)
        {
            if (e.Day.Date < DateMin)
            {
                e.Day.IsSelectable = false;
                e.Cell.ForeColor = System.Drawing.Color.Gray;
                e.Cell.Font.Strikeout = true;
            }
        }
        protected void c1_SelectionChanged(object sender, EventArgs e)
        {
            PopupControlExtender pce = AjaxControlToolkit.PopupControlExtender.GetProxyForCurrentPopup(Page);
            pce.Commit((sender as Calendar).SelectedDate.ToShortDateString());
        }
        protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
        {
                try
                {
                    String error = "";
                    args.IsValid = true;
                    int origin = int.Parse(txtPostCodeOrigin.Text.Trim());
                    int des = int.Parse(txtPostCodeInput.Text.Trim());

                    if (!CheckPostcodeAndAdress(origin))
                    {
                        args.IsValid = false;
                        error = "Check your post code Origin";
                    }
                    if (!CheckPostcodeAndAdress(des))
                    {
                        args.IsValid = false;
                        error = error + "<br//>" + "Check your post code destination";
                    }
                    CVPostCodeOri.ErrorMessage = error;
                }catch(Exception ex)
                {
                    args.IsValid = false;
                    CVPostCodeOri.ErrorMessage = "Invalid Input ( post code)";
                }
            }
        
    }
}